package com.dfxy.blog.listener;

import com.dfxy.blog.dao.BlogDao;
import com.dfxy.blog.dao.UserDao;
import com.dfxy.blog.entity.Blog;
import com.dfxy.blog.entity.User;
import com.dfxy.blog.window.MainWindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;

public class PublishActionListener implements ActionListener {

    private JTextArea textAreaContent;
    private String username;
    private Connection con;
    private BlogDao blogDao;
    private Component parentComponent;
    private MainWindow mainWindow;

    public PublishActionListener(JTextArea textAreaContent, String username, Connection con, BlogDao blogDao, Component parentComponent, MainWindow mainWindow) {
        this.textAreaContent = textAreaContent;
        this.username = username;
        this.con = con;
        this.blogDao = blogDao;
        this.parentComponent = parentComponent;
        this.mainWindow = mainWindow;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            // 1970.1.1 00:00
            Date publishTime = new Date(System.currentTimeMillis());
            Blog publishResultBlog = blogDao.publish(
                    con,
                    new Blog(username, textAreaContent.getText(), publishTime, 0)
            );

            if (publishResultBlog == null) {
                JOptionPane.showMessageDialog(parentComponent, "博客发布失败");
            } else {
                JOptionPane.showMessageDialog(parentComponent, "博客发布成功");

                java.util.List<Blog> blogList = blogDao.blogList(con);
                mainWindow.updateBlogList(blogList);
            }

            mainWindow.publishInit();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
}
